import { _decorator, AudioClip, Component, Touch, Node, randomRangeInt, tween, Tween, UIOpacity, UITransform, v3, Vec3 } from 'cc';
const { ccclass, property } = _decorator;

import { SSS_Consts } from "../../../../Script/Data/SSS_Consts";
import { bdlMgr } from "../../../../Script/Manager/BundleManager_S";
import DragTetris_CardFunctions from "../Common/DragTetris_CardFunctions";
import DragTetris_GameConfig from "../Data/DragTetris_GameConfig";
import { DragTetris_GameData } from "../Data/DragTetris_GameData";
import { DragTetris_BlockType, DragTetris_PosType } from "../Data/DragTetris_GameEnum";
import DragTetris_GameManager from "../Manager/DragTetris_GameManager";
import DragTetris_UIManager from "../Manager/DragTetris_UIManager";
import DragTetris_GamePanel from "../UI/DragTetris_GamePanel";
import DragTetris_Block from "./DragTetris_Block";
import DragTetris_Grid from "./DragTetris_Grid";
import { SSS_AudioManager } from 'db://assets/Script/Manager/SSS_AudioManager';

@ccclass('DragTetrisBlockGroup')
export default class DragTetris_BlockGroup extends Component {
    @property(Node)
    main: Node | null = null;
    id: number = 0;
    x: number = 0;
    y: number = 0;
    length: number = 1;
    type: DragTetris_BlockType = DragTetris_BlockType.NORMAL;
    color: number = 0;
    newPosition: Vec3;
    initPosition: Vec3;
    isDead: boolean = false;
    startPos;
    block_list: DragTetris_Block[] = [];
    minScale: number = 0.5;
    canMove: boolean = true;
    posType: DragTetris_PosType;

    init_pos_x: number = 0;
    init_pos_y: number = 0;

    onLoad(): void {
    }
    //    // 初始化
    init(_id: number, _x: number, _y: number, _color: number, _posType: DragTetris_PosType) {
        this.id = _id;
        // this.type = _type;
        this.x = _x;
        this.y = _y;
        this.color = _color;
        this.posType = _posType;

        this.node.active = true;
        this.node.scale = v3(this.minScale, this.minScale, this.minScale);

        // this.SetColor();
        // this.SetAngle();

        this.node.position = v3(0, 0, 0);

        this.startPos = this.node.position;

        this.init_pos_x = this.node.position.x;
        this.init_pos_y = this.node.position.y;

        // this.block_list = this.group.getComponentsInChildren(Block);
        this.InitBlockList();

        this.AddListener();
    }
    //    // 只序列化需要的属性
    toJSON() {
        return {
            id: this.id,
            x: this.x,
            y: this.y,
            color: this.color,
            posType: this.posType,
            // _class: 'MyClass' // 添加类标识以便反序列化
        };
    }
    //    // 设置所有子物体可见或者不可见
    SetAllChildrenAtive(parent: Node, active: boolean) {
        for (let i = 0; i <= parent.children.length - 1; i++) {
            let child: Node = parent.children[i];
            child.active = active;
        }
    }
    InitBlockList() {
        this.SetAllChildrenAtive(this.main, false);
        let main = this.main.children[this.id];
        main.active = true;
        main.position = v3(0, 0, 0);

        this.block_list = main.getComponentsInChildren(DragTetris_Block);

        for (let index = 0; index < this.block_list.length; index++) {
            const block = this.block_list[index];
            block.color = this.color;
            block.RefreshSprite();
        }
    }
    SetColor() {
        let colors = [0, 1, 2, 3, 4];
        let random_index = randomRangeInt(0, colors.length);
        this.color = colors[random_index];
    }
    SetAngle() {
        let angles = [0, 90, 180, 270];
        let random_index = randomRangeInt(0, angles.length);
        let angle = angles[random_index];
        this.node.angle = angle;
    }
    AddListener() {
        this.node.on(Node.EventType.TOUCH_START, this.TOUCH_START, this);
        this.node.on(Node.EventType.TOUCH_MOVE, this.TOUCH_MOVE, this);
        this.node.on(Node.EventType.TOUCH_END, this.TOUCH_END, this);
        this.node.on(Node.EventType.TOUCH_CANCEL, this.TOUCH_END, this);
    }
    //    // 
    GetLeftBlock(_block: DragTetris_Block) {
        const list = [];

        for (let index = 0; index < this.block_list.length; index++) {
            const block = this.block_list[index];
            if (_block !== block) {
                list.push(block);
            }
        }

        return list;
    }
    time
    async TOUCH_START(t: Touch) {
        // console.log(`TOUCH_START`);

        this.time = new Date().getTime();


        bdlMgr.getRes<AudioClip>(SSS_Consts.BundleName.AUDIO, `audio/掉落音效`, AudioClip).then(res => {
            SSS_AudioManager.Instance.playSFX(res, false);
        });

        DragTetris_CardFunctions.AllGridSelect(false);

        if (!this.canMove) {
            return;
        }

        // let time2 = new Date().getTime();
        // let diff_time = time2 - this.time;
        // if (diff_time <= 300) {

        // }

        // this.scheduleOnce(() => {
        //     this.node.y += 400;
        // }, 0.1)


        // console.log(this.x, this.y, this.length);

        DragTetris_GameData.IsMouseDown = true;
        this.node.scale = v3(1, 1, 1);
        const location = t.getLocation();
        // const location = t.getUILocation();
        this.initPosition = this.node.position;
        DragTetris_GameData.StartPos = location;

        // console.log(`TOUCH_START---`);
    }
    TOUCH_MOVE(t) {
        DragTetris_CardFunctions.AllGridSelect(false);

        if (!this.canMove) {
            return;
        }

        if (DragTetris_GameData.IsMouseDown === true) {
            // const location = t.getLocation();
            // const location = t.getUILocation();

            const delta = t.getUIDelta();
            const position = this.node.position;
            this.node.setPosition(position.x + delta.x, position.y + delta.y);


            // DragTetris_GameData.CurrentPos = location;
            // let diff = v3(DragTetris_GameData.CurrentPos.sub(DragTetris_GameData.StartPos));

            // let current = new Vec3(DragTetris_GameData.CurrentPos.x, DragTetris_GameData.CurrentPos.y, 0);
            // let start = new Vec3(DragTetris_GameData.StartPos.x, DragTetris_GameData.StartPos.y, 0);

            // let diff = Vec3.subtract(new Vec3(), current, start);


            let scale = 1;

            // let pos = v3(this.initPosition.x + diff.x * scale, this.initPosition.y + diff.y * scale, this.initPosition.z); // this.initPosition.add(diff);
            // this.node.position = pos;

            {
                for (let index = 0; index < this.block_list.length; index++) {
                    const block: DragTetris_Block = this.block_list[index];

                    // let p1 = block.node.convertToWorldSpaceAR(v2(0, 0));
                    // let p2 = DragTetris_UIManager.Instance.Root_grid.convertToNodeSpaceAR(p1);
                    let p1 = block.node.getComponent(UITransform)!.convertToWorldSpaceAR(new Vec3(0, 0, 0));
                    let p2 = DragTetris_UIManager.Instance.Root_grid.getComponent(UITransform).convertToNodeSpaceAR(p1);


                    const x_new = block.GetXByX(p2.x);
                    const y_new = block.GetXByY(p2.y);

                    let grid: DragTetris_Grid = DragTetris_CardFunctions.GetGrid(x_new, y_new)
                    if (grid && grid.block === null) {
                        grid.Select(true);
                    }
                }
            }
        }
    }
    转圈() {
        tween(this.node)
            // .by(0.1, { angle: -90 }, { easing: "" })
            .by(0.1, { angle: -90 })
            .call(() => {
            })
            .start();

        // bdlMgr.getRes<AudioClip>(SSS_Consts.BundleName.AUDIO, `audio/旋转音效`, AudioClip).then(res => {
        //     AudioManager.Instance.playSFX(res, false);
        // });
    }
    async TOUCH_END() {
        // console.log("TOUCH_END");

        if (!this.canMove) {
            return;
        }

        let time2 = new Date().getTime();
        let diff_time = time2 - this.time;

        if (diff_time <= 300) {
            this.转圈();
        }
        else {
            bdlMgr.getRes<AudioClip>(SSS_Consts.BundleName.AUDIO, `audio/关卡开始阵列石块下落音效`, AudioClip).then(res => {
                SSS_AudioManager.Instance.playSFX(res, false);
            });
        }

        DragTetris_CardFunctions.AllGridSelect(false);

        DragTetris_GameData.IsMouseDown = false;

        let fun_list = [];
        let isTag: boolean = true;
        for (let index = 0; index < this.block_list.length; index++) {
            const block: DragTetris_Block = this.block_list[index];

            // let p1 = block.node.convertToWorldSpaceAR(v2(0, 0));
            // let p2 = DragTetris_UIManager.Instance.Root_grid.convertToNodeSpaceAR(p1);

            let p1 = block.node.getComponent(UITransform)!.convertToWorldSpaceAR(new Vec3(0, 0, 0));
            let p2 = DragTetris_UIManager.Instance.Root_grid.getComponent(UITransform)!.convertToNodeSpaceAR(p1);


            const x_new = block.GetXByX(p2.x);
            const y_new = block.GetXByY(p2.y);

            let grid: DragTetris_Grid = DragTetris_CardFunctions.GetGrid(x_new, y_new)
            if (grid && grid.block === null) {
                let fun = () => {
                    // this.x = x_new;
                    this.y = y_new;
                    grid.block = block;
                    block.grid = grid;
                    block.node.parent = block.grid.node;
                    block.node.position = v3(0, 0, 0);
                    // block.node.position = block.grid.node.position;

                }
                fun_list.push(fun);
            }
            else {
                isTag = false;
                break;
            }
        }

        if (isTag) {
            for (let index = 0; index < fun_list.length; index++) {
                const fun = fun_list[index];
                fun();
            }

            this.canMove = false;
            this.posType = DragTetris_PosType.方格中;
            // this.node.destroy();

            // let x = this.x;
            // console.log(`this.x`, this.x);

            await DragTetris_CardFunctions.随机创建一个BlockGroup(this.x);
            DragTetris_GameData.SaveData();

            DragTetris_GameData.SaveGridData();

            // let y = -1;
            // let color = DragTetris_CardFunctions.GetRandomColor();
            // let id = DragTetris_randomRangeInt(0, DragTetris_GameConfig.方块种类数量);
            // let posType = DragTetris_PosType.下面操作台中;
            // let newBlockGroup = DragTetris_CardFunctions.CreateBlockGroup(id, x, y, color, posType);

            // {
            //     let d1 = 500;
            //     let d2 = 4;
            //     // blockGroup.node.y -= d1;
            //     let p = newBlockGroup.node.position;
            //     newBlockGroup.node.setPosition(p.x, p.y - d1, p.z);
            //     tween(newBlockGroup.node)
            //         .by(0.4, { position: v3(0, d1 + d2) })
            //         .by(0.1, { position: v3(0, -d2) })
            //         // .by(0.4, { y: +(d1 + d2) }, { easing: "" })
            //         // .by(0.1, { y: -d2 }, { easing: "" })
            //         .call(() => {
            //         })
            //         .start();
            // }

            this.node.destroy();

            DragTetris_GameManager.Main();
        }
        else {
            this.node.setPosition(v3(this.init_pos_x, this.init_pos_y, this.node.position.z));
            this.node.setScale(this.minScale, this.minScale, this.minScale);

            // this.node.position = this.startPos;
            // this.node.scale = v3(this.minScale, this.minScale, this.minScale);
        }
    }
    GetXByX(x_pos: number) {
        let x = (x_pos - (-DragTetris_GameConfig.W / 2 + this.node.getComponent(UITransform).width / 2)) / DragTetris_GameConfig.size + 0.5;
        let x_int = Math.floor(x);
        return x_int;
    }
    GetXByY(y_pos: number) {
        let y = (y_pos - (-DragTetris_GameConfig.H / 2 + this.node.getComponent(UITransform).height / 2)) / DragTetris_GameConfig.size + 0.5;
        let x_int = Math.floor(y);
        return x_int;
    }
    //    // 初始化单元宽高
    initWidthAndHeight(cardWidth?: number, cardHeight?: number) {
    }
    //    // 初始化位置
    InitPosition(_x = null, _y = null) {

    }
    GetPositionXByX(_x) {
        let x = -DragTetris_GameConfig.W / 2 + this.node.getComponent(UITransform).width / 2 + DragTetris_GameConfig.size * _x;
        return x;
    }
    DestroyAnimation(callback: Function = null) {
        if (this.isDead) {
            return;
        }

        this.isDead = true;

        const score = DragTetris_CardFunctions.GetScore();
        DragTetris_GameData.SetScore(DragTetris_GameData.GetScore() + score);

        DragTetris_GameData.UpdateScore();
        // GameFunctions.LevelUp();
        DragTetris_GamePanel.Instance.Refresh();

        let uiOpacity = this.node.getComponent(UIOpacity) || this.node.addComponent(UIOpacity);
        tween(uiOpacity)
            .to(0.1, { opacity: 0 })
            .call(() => {
                this.node.destroy();
                if (callback) {
                    callback();
                }
            })
            .call(() => { })
            .start();
    }
    Destroy() {
        this.node.destroy();
    }
    // ToMapData() {
    //     let data: any = {};
    //     data.id = this.id;
    //     data.type = this.type;
    //     data.x = this.x;
    //     data.y = this.y;
    //     data.length = this.length;
    //     data.color = this.color;
    //     return data;
    // }
    GetNodeWorldPostation(_node: Node): Vec3 {
        let pos: Vec3 = v3();
        if (_node.parent == null) {
            pos = v3(_node.getPosition());
        } else {
            // pos = v3(_node.parent.convertToWorldSpaceAR(_node.getPosition()));
            pos = _node.getWorldPosition();
        }
        return pos;
    }
    Flash() {
        Tween.stopAllByTarget(this.node);
        tween(this.node)
            .repeatForever(
                tween()
                    .to(0.4, { scale: 0.6 })
                    .to(0.4, { scale: 0.5 })
            )
            .start()
    }
}